package com.cf.chat.client;
import com.cf.chat.util.CloseUtil;
import java.io.DataInputStream;
import java.io.IOException;
import java.net.Socket;
/**
 * @Auther: chenf
 * @Date: 2020/07/28/15:35
 * @Description:客户端接收服务器端发送的信息
 */
public class Receive implements Runnable {
    // 定义用于接收数据的数据流
    private DataInputStream dis;
    private boolean flag = true;

    /**
     * 把从客户端接收到的输入流数据传给dis
     * @param client
     */
    public Receive(Socket client) {
        try {
            dis = new DataInputStream(client.getInputStream());
        } catch (IOException e) {
            flag = false;
            CloseUtil.closeAll(dis, client);
        }
    }

    /**
     * 读取dis中的输入流对象传给str并返回
     * @return
     */
    private String getMessage() {
        String str = "";
        try {
            str = dis.readUTF();
        } catch (IOException e) {
            flag = false;
            CloseUtil.closeAll(dis);
        }
        return str;
    }

    /**
     * 执行Client进程的run方法
     */
    @Override
    public void run() {
        while (flag) {
            System.out.println(this.getMessage());
        }
    }
}
